<template>
  <div class="btn-coupon-wrapper g-flex-sb-start">
    <div class="left-box">
      <div class="title">发放优惠券</div>
      <div class="coupon-list g-flex-row">
        <coupon-template :hasCheck="true" class="coupon-template" v-for="(item,index) in couponOptions" :key="index" :info="item" :index="index" @change="changeCoupon"></coupon-template>
      </div>
      <el-form :model="magicForm" ref="magicForm" label-width="90px" class="magic-form" size="mini">
        <el-form-item label="领券上限:">
          <span class="text">同一面额每人每天可领取1张 </span>
        </el-form-item>
        <el-form-item label="使用上限:">
          <span class="text">每笔订单最多可使用1张商家券</span>
        </el-form-item>
        <el-form-item label="何时可用:">
          <span class="text">领取后当天开始</span>
        </el-form-item>
        <el-form-item label="活动时间:">
          <el-date-picker 
            v-model="activeTime" 
            type="daterange"
            value-format="yyyy-MM-dd" 
            :default-time="['00:00:00', '23:59:59']"
            range-separator="至"   
            start-placeholder="开始时间" 
            end-placeholder="结束时间" 
            :picker-options="pickerOptions" 
            @change="(value) => changeTime(value)"
            :clearable="false"
            :editable="false">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div class="btn-coupon-box">
        <template v-if="activeId">
          <el-button @click="$router.push({path:'/dataAnalyze/dataAnalyze_index'})">取消</el-button>
          <el-button type="primary" @click="confirmTips">保存</el-button>
        </template>
        <el-button v-else type="primary" @click="confirmTips" class="btn-coupon">一键配置</el-button>
      </div>
    </div>
    <div class="right-box g-flex-column-c ">
      <div class="title">APP效果示例</div>
      <img class="case-img" :src="caseUrl" />
    </div>
  </div>
</template>
<script>
import {ossUrl} from '@/utils/config'
import CouponTemplate from '../../components/coupon/template'
import { defaultCoupon, getDefaultTimeApi, createCouponActiveApi, getCouponActiveDetailApi, updateCouponActiveApi, disabledCouponDateApi, getCouponLimitApi } from '@/api/marketShop'
import { mapGetters } from 'vuex'
import _ from 'lodash'
import MD5 from 'md5'
import moment from 'moment'

export default {
  components:{
    CouponTemplate
  },
  data(){
    return{
      magicForm:{},
      activeTime:'',
      caseUrl: `${ossUrl}market/ppt-coupon.png`,
      couponOptions:[],
      selectedOptions:[],
      activeId:'',
      disabledDate:[],
      couponRulesLimt: {},
      selectDate:''
    }
  },
  computed: {
    ...mapGetters(['gasInfo']),
    pickerOptions () {
      const { duration = {} } = this.couponRulesLimt
      return {
        onPick: ({ maxDate, minDate }) => {
          this.selectDate = minDate.getTime()
          if (maxDate) {
            this.selectDate = ''
          }
        },
        disabledDate: (time) => {
          const currTime = moment().format('YYYY-MM-DD')
          const date = moment(time).format('YYYY-MM-DD')
          if (this.selectDate) {
            const maxTime = moment(this.selectDate).add(duration.max, 'days').format('YYYY-MM-DD')
            const minTime = moment(this.selectDate).subtract(duration.max, 'days').format('YYYY-MM-DD')
            return moment(date).isBefore(minTime) || moment(date).isBefore(currTime) || moment(date).isAfter(maxTime) || this.disabledDate.includes(date)
          } else {
            return moment(date).isBefore(currTime) || this.disabledDate.includes(date)
          }
        }
      }
    }
  },
  created(){
    this.initPage()
  },
  methods:{
    //初始化
    initPage(){
      this.activeId = this.$route.query.activeId
      this.getCouponInfo()
      this.getCouponLimit()
      this.getDisabledDate()
    },
    //提交
    submitForm(){
      const couponList = this.couponOptions.filter(item=>item.isCheck)
      if(this.activeId){
        this.updateActive(couponList,this.activeId)
      }else{
        this.createActive(couponList)
      }
    },
    //时间change
    changeTime (value, startTime = 'startTime', endTime = 'endTime') {
      if (value) {
        this.magicForm[startTime] = value[0]
        this.magicForm[endTime] = value[1]
      } else {
        this.magicForm[startTime] = ''
        this.magicForm[endTime] = ''
      }
    },
    //获取通用优惠券
    async getCouponInfo(){
      try{
        const { code, result} = await defaultCoupon()
        if( code !== 200 ) return
        this.couponOptions = result['3']
      }catch(e){
        console.log(e)
      }finally{
        if(this.activeId){
          this.getActiveDetail(this.activeId)
        }else{
          this.initCreateCoupon()
          this.getDefaultTime()
        }
      }
    },
    //获取默认时间（创建时）
    async getDefaultTime(){
      try{
        const { code, result} = await getDefaultTimeApi({gasId:this.gasInfo.gasId})
        if( code !== 200 ) return
        this.initActiveTime(result)
      }catch(e){
        console.log(e)
      }
    },
    //获取活动详情（修改）
    async getActiveDetail(activeId){
      try{
        const { code, result } = await getCouponActiveDetailApi({activeId})
        if( code !== 200 ) return
        const { couponList, startTime, endTime} = result
        this.initSelectedCoupon(couponList)
        this.initActiveTime({startTime,endTime})
      }catch(e){
        console.log(e)
      }
    },
    //创建活动
    async createActive(couponList){
      const data = {
        gasId: this.gasInfo.gasId,
        ...this.magicForm,
        couponListJson: JSON.stringify(couponList)
      }
      try{
        const {code} = await createCouponActiveApi(data)
        if(code !== 200) return
        this.gotoList()
      }catch(e){
        console.log(e)
      }
    },
    //修改活动
    async updateActive(couponList,activeId){
      const data = {
        activeId,
        gasId: this.gasInfo.gasId,
        ...this.magicForm,
        couponListJson: JSON.stringify(couponList)
      }
      try{
        const { code } = await updateCouponActiveApi(data)
        if(code !== 200) return
        this.$message.success('修改成功')
        this.gotoList()
      }catch(e){
        console.log(e)
      }
    },
    //初始化活动优惠券（修改）
    initSelectedCoupon(selectedArr){
      const tempOptons = _.cloneDeep(this.couponOptions)
      tempOptons.forEach((item,index) => {
        let isCheck = false
        for(let i=0, len = selectedArr.length; i<len; i++){
          let itemMd5 = MD5(JSON.stringify(item))
          let valMd5 = MD5(JSON.stringify(selectedArr[i]))
          if(itemMd5 === valMd5){
            isCheck = true
            break
          }
        }
        this.$set(this.couponOptions[index],'isCheck',isCheck)
      })
    },
    //初始化活动优惠券（创建）
    initCreateCoupon(){
      const tempOptons = _.cloneDeep(this.couponOptions)
      tempOptons.forEach((item,index) => {
        let isCheck = true
        this.$set(this.couponOptions[index],'isCheck',isCheck)
      })
    },
    //优惠券选择与否
    changeCoupon({index,isCheck}){
      const couponList = this.couponOptions.filter(item=>item.isCheck)
      if(couponList.length === 1 && isCheck === true) return
      this.couponOptions[index].isCheck = !isCheck
    },
    //初始化活动时间
    initActiveTime({startTime='',endTime=''}){
      let start = moment(startTime).format("YYYY-MM-DD HH:mm:ss")
      let end = moment(endTime).format("YYYY-MM-DD HH:mm:ss")
      this.activeTime = [start,end]
      this.changeTime([startTime,endTime])
    },
    //获取不可选的活动时间
    async getDisabledDate () {
      try{
        const data = {gasId:this.gasInfo.gasId}
        if(this.activeId){
          data.activeId = this.activeId
        }
        const res = await disabledCouponDateApi(data)
        if (res.code !== 200) return
        const { localDates = [] } = res.result
        this.disabledDate = localDates
      }catch(e){
        console.log(e)
      }
    },
    //获取活动创建相关限制
    async getCouponLimit () {
      const { code, result } = await getCouponLimitApi()
      if (code !== 200) return
      this.couponRulesLimt = result
    },
    gotoList(){
      this.$router.push({ path: '/marketCenter/activitySuccess' })
    },
    //提交提示
    confirmTips(){
      this.$confirm(this.activeId?'是否确认修改本次店铺领券活动？': '是否创建本次店铺领券活动？', this.activeId?'修改活动':'创建活动', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitForm()
      }).catch(() => {
                  
      })
    }
  }
}
</script>
<style lang="less" scoped>
.btn-coupon-wrapper{
  background: #ffffff;
  padding: 24px 29px;
  .left-box{
    width: 75%;
    .text{
      font-size: 14px;
      font-family: PingFangSC-Regular, PingFang SC;
      color: #666666;
    }
    .coupon-list{
      width: 100%;
      height: 115px;
      margin: 15px 0 20px;
    }
    .coupon-template{
      width: 310px;
      height: 121px;
    }
    .btn-coupon-box{
      padding-left: 15px;
      .btn-coupon{
        width: 216px;
        height: 48px;
        font-size: 20px;
        font-family: PingFangSC-Semibold, PingFang SC;
        font-weight: 600;
        background: #4B7EFE;
      }
    }
  }
  .right-box{
    width: 25%;
    .case-img{
      width: 258px;
      height: 467px;
    }
  }
  .title{
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
    color: #222222;
    margin-bottom: 10px;
  }
  /deep/ .el-form-item {
    margin-bottom: 20px;
  }
}
</style>